import { Request } from '../models/request.model';

/**
 * 消息类型枚举
 */
export enum MessageType {
  CAPTURE_REQUEST = 'capture_request',
  SEND_REQUEST = 'send_request',
  SAVE_REQUEST = 'save_request',
  GET_ACTIVE_TAB_REQUEST = 'get_active_tab_request',
  GET_TAB_REQUESTS = 'get_tab_requests',
  REQUEST_CAPTURED = 'request_captured'
}

/**
 * 消息接口
 */
export interface Message {
  type: MessageType;
  data?: any;
}

/**
 * 消息服务类
 * 负责处理插件不同部分之间的通信
 */
export class MessageService {
  /**
   * 发送消息
   * @param message 消息对象
   * @returns 响应Promise
   */
  static async sendMessage(message: Message): Promise<any> {
    try {
      return await chrome.runtime.sendMessage(message);
    } catch (error) {
      console.error('Error sending message:', error);
      throw error;
    }
  }

  /**
   * 监听消息
   * @param callback 回调函数
   */
  static addListener(callback: (message: Message, sender: chrome.runtime.MessageSender, sendResponse: (response?: any) => void) => void): void {
    chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
      callback(message, sender, sendResponse);
      return true; // 表示会异步发送响应
    });
  }

  /**
   * 向内容脚本发送消息
   * @param tabId 标签页ID
   * @param message 消息对象
   * @returns 响应Promise
   */
  static async sendToContentScript(tabId: number, message: Message): Promise<any> {
    try {
      return await chrome.tabs.sendMessage(tabId, message);
    } catch (error) {
      console.error('Error sending message to content script:', error);
      throw error;
    }
  }

  /**
   * 捕获当前标签页的请求
   * @returns 请求对象Promise
   */
  static async captureActiveTabRequest(): Promise<Request | null> {
    try {
      // 获取当前活动标签
      const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tabs.length === 0) {
        throw new Error('没有活动标签页');
      }
      
      const activeTab = tabs[0];
      if (!activeTab.id) {
        throw new Error('无法获取标签页ID');
      }
      
      // 向内容脚本发送消息
      const response = await this.sendToContentScript(activeTab.id, {
        type: MessageType.CAPTURE_REQUEST
      });
      
      if (!response || !response.request) {
        return null;
      }
      
      return new Request(response.request);
    } catch (error) {
      console.error('Error capturing active tab request:', error);
      return null;
    }
  }

  /**
   * 获取标签页所有请求
   * @param tabId 可选的标签页ID，如果不提供则使用当前活动标签页
   * @returns 响应Promise
   */
  static async getTabRequests(tabId?: number): Promise<any> {
    return this.sendMessage({
      type: MessageType.GET_TAB_REQUESTS,
      data: { tabId }
    });
  }

  /**
   * 发送请求
   * @param request 请求对象
   * @returns 响应Promise
   */
  static async sendRequest(request: Request): Promise<any> {
    return this.sendMessage({
      type: MessageType.SEND_REQUEST,
      data: { request }
    });
  }

  /**
   * 保存请求
   * @param request 请求对象
   * @returns 响应Promise
   */
  static async saveRequest(request: Request): Promise<any> {
    return this.sendMessage({
      type: MessageType.SAVE_REQUEST,
      data: { request }
    });
  }

  /**
   * 获取当前活动标签页的URL
   * @returns URL Promise
   */
  static async getActiveTabUrl(): Promise<string | null> {
    try {
      const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
      if (tabs.length > 0 && tabs[0].url) {
        return tabs[0].url;
      }
      return null;
    } catch (error) {
      console.error('Error getting active tab URL:', error);
      return null;
    }
  }
} 